Controlling the Size of an Element

Description

You can control the element size by using the size-related properties described below.

  • width
    height
    Set the width and height for the element.
    Value: auto or length or %
  • min-width
    min-height
    Set the minimum acceptable width or height for the element.
    Value: auto or length or %
  • max-width
    max-height
    Set the maximum acceptable width or height for the element.
    Value: auto length %
  • box-sizing
    Sets which part of an element's box is used for sizing.
    Value: content-box or padding-box or border-box or margin-box

The default value for all these properties is auto and the browser will figure out the width and height of the element.

You can specify sizes explicitly using lengths or percentages. The percentage values are calculated from the width of the containing block even when dealing with height.

Example

The following code shows how you can set the size of an element.


<!DOCTYPE HTML>
<html>
<head>
<style type="text/css">
div {<!--   w w  w .  ja  v a 2s  .  c  o  m-->
  width: 75%;
  height: 100px;
  border: thin solid black;
}

img {
  background: lightgray;
  border: 4px solid black;
  margin: 2px;
  height: 50%;
}

#first {
  box-sizing: border-box;
  width: 50%;
}

#second {
  box-sizing: content-box;
}
</style>
</head>
<body>
  <div>
    <img id="first" src="http://www.java2s.com/style/download.png" alt="small  banana">
    <img id="second" src="http://www.java2s.com/style/download.png" alt="small  banana">
  </div>
</body>
</html>

Click to view the demo

There are three elements in the body. A div element contains two img elements. The div element,whose width set to 75%, is a child of the body element.

The div element will have 75% of the width of the containing block, which is the body content box.

If the browser window is resized, then the body element will be resized and the div element will also be resized to preserve the 75% relationship.

The height of the div element is 100px. It is an absolute value and won't change as the containing block is resized.

The width of the img element is 50% of the containing block.





















Home »
  HTML CSS »
    CSS »




CSS Introduction
CSS Background
CSS Border
CSS Box Layout
CSS Text
CSS Font
CSS Form
CSS List
CSS Selectors
CSS Others
CSS Table